/**
 * @description 微信相关 controller
 */

const {
    appid,
    secret
}  = require('../conf/constant')

const {
    queryUser
} = require('../services/wx')

const {
    getUserInfo
} = require('../services/user')

const { SuccessModel, ErrorModel } = require('../model/ResModel')
const {
    UserNoExist
} =require('../model/ErrorInfo')

const koaRequest = require('koa2-request')

/**
 * 
 * @param {string} js_code 从接口获取的code
 */
async function getWxOpenId(js_code) {
    let res = await koaRequest({//向微信传递code获取openId
        url:'https://api.weixin.qq.com/sns/jscode2session',
        method: 'get',
        qs: {
            appid,
            secret,
            js_code,
            grant_type:'authorization_code'
        }
    })
    if(res.statusCode == 200){
        console.log(JSON.stringify(res));
        const {
            openid:openId,
            session_key:sessionKey
        } = JSON.parse(res.body)
        const result = await queryUser(openId)
        if(result == null){
            return new ErrorModel(UserNoExist,{
                openId,
                sessionKey
            })
        }
        const userInfo = await getUserInfo({openId})
        return new SuccessModel({
            openId,
            sessionKey,
            userInfo
        })
    }
}

module.exports = {
    getWxOpenId
}